/**
 * 日期工具函数
 */

/**
 * 格式化日期
 * @param date 日期字符串或Date对象
 * @param format 格式化模板，默认为 'YYYY-MM-DD HH:mm:ss'
 * @returns 格式化后的日期字符串
 */
export function formatDate(
  date?: string | Date | null,
  format = "YYYY-MM-DD HH:mm:ss",
): string {
  if (!date) return "";

  const d = typeof date === "string" ? new Date(date) : date;

  if (isNaN(d.getTime())) return "";

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  const seconds = String(d.getSeconds()).padStart(2, "0");

  return format
    .replace("YYYY", String(year))
    .replace("MM", month)
    .replace("DD", day)
    .replace("HH", hours)
    .replace("mm", minutes)
    .replace("ss", seconds);
}

/**
 * 获取相对时间描述
 * @param date 日期字符串或Date对象
 * @returns 相对时间描述，如"刚刚"、"5分钟前"等
 */
export function getRelativeTime(date: string | Date): string {
  if (!date) return "";

  const d = typeof date === "string" ? new Date(date) : date;
  const now = new Date();
  const diff = now.getTime() - d.getTime();

  if (diff < 60000) return "刚刚";
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`;

  return formatDate(d, "YYYY-MM-DD");
}

/**
 * 判断日期是否为今天
 * @param date 日期字符串或Date对象
 * @returns 是否为今天
 */
export function isToday(date: string | Date): boolean {
  if (!date) return false;

  const d = typeof date === "string" ? new Date(date) : date;
  const today = new Date();

  return d.toDateString() === today.toDateString();
}

/**
 * 获取日期范围
 * @param days 天数，负数表示过去，正数表示未来
 * @returns 日期范围数组 [开始日期, 结束日期]
 */
export function getDateRange(days: number): [string, string] {
  const today = new Date();
  const targetDate = new Date(today.getTime() + days * 24 * 60 * 60 * 1000);

  if (days < 0) {
    return [
      formatDate(targetDate, "YYYY-MM-DD"),
      formatDate(today, "YYYY-MM-DD"),
    ];
  } else {
    return [
      formatDate(today, "YYYY-MM-DD"),
      formatDate(targetDate, "YYYY-MM-DD"),
    ];
  }
}
